package com.bosssoft.trainee.security.bo;

import com.bosssoft.trainee.mbg.dto.UserDTO;
import com.bosssoft.trainee.mbg.po.Resource;
import com.bosssoft.trainee.mbg.po.User;
import com.bosssoft.trainee.mbg.vo.UserVO;
import com.bosssoft.trainee.security.bo.deserializer.CustomAuthorityDeserializer;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: wuxin
 * @Project: rbac
 * @Date: 2022/6/23
 * @Description:
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserBO implements UserDetails {
    private transient UserVO user;

    private transient List<Resource> resourceList;

    @Override
    @JsonDeserialize(using = CustomAuthorityDeserializer.class)
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return resourceList.stream()
                .map(role ->new SimpleGrantedAuthority(role.getId()+":"+role.getName()))
                .collect(Collectors.toList());
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return user.getState()!=2;
    }
}
